<?php
/**
 * Fastapp.
 * 3/27/24
 * @Author deepsea
 * @Contact telegram:deepsea159
 */

namespace App\Fastapp\Api\Service\Account;

use App\Fastapp\Api\Service\BaseService;
use App\Fastapp\Exception\TipException;
use App\Fastapp\Model\Account;
use App\Fastapp\Model\AccountInfo;
use App\Fastapp\Model\AccountRealname;
use App\Fastapp\Model\FastappRealname;

class RealnameService extends BaseService
{
    public function authentication(array $data): array
    {
        if (empty($data['user_id'])) {
            $uid = get_uid();
        } else {
            $uid = $data['user_id'];
            if (!Account::query()->where(['gene_id' => $uid])->exists()) throw new TipException(fastapp_t('fastapp.invalid_operation'));
        }
        $data['id_no'] = strtoupper($data['id_no']);
        $md = FastappRealname::query()->where(['id_no' => $data['id_no']])->first();
        if (!$md) $md = new FastappRealname();
        $md->fill($data);
        if ($md->save()) {
            $map = ['user_id' => $uid, 'type' => $data['type'] ?? 1];
            $ur = AccountRealname::query()->where($map)->first();
            if (!$ur) $ur = new AccountRealname();
            $ur->fill(array_merge($map, ['realname_id' => $md->id]));
            $ur->save();
            AccountInfo::query()->where(['user_id' => $uid])->update(['name' => $md->name]);
            return [
                'created_at' => $md->created_at->toDateTimeString(),
                'updated_at' => $md->updated_at->toDateTimeString(),
                'user_id' => $uid
            ];
        }
        throw new TipException(fastapp_t('fastapp.authentication_failed'));
    }

    public function check(array $param = []): array
    {
        $uid = $param['user_id'] ?? get_uid();
        $map = ['user_id' => $uid, 'type' => 1];
        $md = AccountRealname::query()->with(['realname:id,status'])->where($map)->first();
        $data['info'] = $md ? 1 : 0;//资料0未填1已填
        $data['status'] = $data['info'] ? $md->realname->status : 0;
        return $data;
    }

    public function detail(int $uid = 0, int $type = 1): array
    {
        $map = ['user_id' => $uid ?: get_uid(), 'type' => $type];
        $md = AccountRealname::query()->with(['realname'])->where($map)->first();
        return $md ? $md->realname->toArray() : [];
    }
}